<script setup lang="ts">
import { ref, type PropType } from 'vue'
import { imgPreview, isVideo } from '@/libs/formatImage'

const previewVideoSrc = ref('')
const $props = defineProps({
  images: { type: Array as PropType<string[]>, default: () => [] },
  width: { type: [String, Number], default: '' },
  height: { type: [String, Number], default: '' },
})
const autoplayVideo = ref(false)

function previewVideoClose() {
  autoplayVideo.value = false
  previewVideoSrc.value = ''
}
function handleImgPreview(src: string, index: number) {
  if (isVideo(src)) {
    previewVideo(src)
  } else {
    imgPreview(index, $props.images)
  }
}
function previewVideo(src: string) {
  previewVideoSrc.value = src
  autoplayVideo.value = true
}
</script>

<template>
  <view class="images">
    <view
      v-for="(i, index) in $props.images"
      :key="index"
      style="margin: 10rpx 10rpx 10rpx 10rpx; position: relative"
      :style="{
        width: $props.width || ($props.images.length === 3 ? 'calc(33.3% - 10rpx * 2)' : 'calc(50% - 10rpx * 2)'),
        height: $props.height || ($props.images.length === 3 ? '220' : '330') + 'rpx',
      }"
    >
      <u-image
        border-radius="14rpx"
        width="100%"
        :height="$props.height || ($props.images.length === 3 ? '220' : '330') + 'rpx'"
        :src="i"
        fade
        duration="450"
        @click="handleImgPreview(i, index)"
      >
      </u-image>
      <view v-if="isVideo(i)" class="autoplay-btn" @click.stop="previewVideo(i)">
        <u-icon name="play-right-fill" size="40rpx" color="#ffffff" />
      </view>
    </view>
    <!-- <u-image
            v-for="(i, index) in $props.images"
            :key="index"
            :width="$props.width || ($props.images.length === 3 ? 'calc(33.3% - 10rpx * 2)' : 'calc(50% - 10rpx * 2)')"
            :height="$props.height || ($props.images.length === 3 ? '220' : '330') + 'rpx'"
            style="margin-top: 20rpx"
            border-radius="14rpx"
            :src="i"
            :fade="true"
            duration="450"
            @click="imgPreview(index, $props.images)"
        /> -->
  </view>
  <u-mask :show="autoplayVideo" :custom-style="{ backgroundColor: '#000', display: 'flex', alignItems: 'center' }" @click="previewVideoClose">
    <video :src="previewVideoSrc" object-fit="contain" class="preview-video" @click.stop="() => {}" />
  </u-mask>
</template>

<style scoped lang="scss">
@include b(images) {
  width: 100%;
  @include flex();
  justify-content: space-between;
  flex-wrap: wrap;
}
@include b(preview-video) {
  width: 100vw;
}
@include b(autoplay-btn) {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  border: 2px solid #fff;
  padding: 5rpx;
  @include flex;
}
</style>
